<template>
  <div class="content-padding">
    <div class="shortMessage-tag">
      <!-- 插入图片的标签 -->
      <img @click="handleTag" src="" />
    </div>
    <div
      @click="handleSelection"
      @input="handleSelection"
      class="shortMessage-div_input edit"
      contenteditable="true"
    >
      
    </div>
    <el-button @click="confirm">确定</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selection: null,
      range: null,
      textNode: null,
      rangeStartOffset: null,
    };
  },
  methods: {
    // 点击要插入的图片
    handleTag(e) {
      const parseDom = this.parseDom(
        `<img @click="handleTag" src="${require("./images/calendarIco4.png")}">`
      );
      // 在光标处插入dom
      this.range.insertNode(parseDom);
      // 光标开始和光标结束重叠
      this.range.collapse(true);
    },
    // 记录光标位置等 （debounce防抖提升性能）
    handleSelection() {
      this.selection = getSelection();
      // 光标对象
      this.range = this.selection.getRangeAt(0);
      // 获取光标对象的范围界定对象
      this.textNode = this.range.startContainer;
      // 获取光标位置
      this.rangeStartOffset = this.range.startOffset;
    },

    // 转dom对象
    parseDom(arg) {
      var objE = document.createElement("div");
      objE.innerHTML = arg;
      return objE.childNodes[0];
    },

    confirm() {
      let result = document.getElementsByClassName(
        "shortMessage-div_input"
      )[0].innerHTML;
      console.log("result", result);
    },
  },
  mounted() {
  
    var edit = document.querySelector(".edit");
    console.log('edit',edit)
    edit.onfocus = function () {
      window.setTimeout(function () {
        var sel, range;
        if (window.getSelection && document.createRange) {
          range = document.createRange();
          range.selectNodeContents(edit);
          range.collapse(true);
          range.setEnd(edit, edit.childNodes.length);
          range.setStart(edit, edit.childNodes.length);
          sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
        } else if (document.body.createTextRange) {
          range = document.body.createTextRange();
          range.moveToElementText(edit);
          range.collapse(true);
          range.select();
        }
      }, 1);
    };
    edit.focus();
  },
};
</script>
<style>
/* .text{
  opacity: 0;
} */
</style>
